package com.yh.csx.crm.service;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.dao.SysFlowConfigMapper;
import com.yh.csx.crm.dao.SysNodeConfigMapper;
import com.yh.csx.crm.dao.SysSalesPermissionMapper;
import com.yh.csx.crm.po.SysFlowConfig;
import com.yh.csx.crm.po.SysNodeConfig;
import com.yh.csx.crm.po.SysSalesPermission;
import com.yh.csx.crm.service.vo.FlowNodeJSON;
import com.yh.csx.crm.service.vo.InputNodePerson;
import com.yh.csx.crm.service.vo.NodePerson;
import com.yh.csx.crm.service.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * InitializeDataService class
 *
 * @author huyalin
 * @date 2019/3/25
 */
@Slf4j
@Service
public class InitializeDataService {
    @Autowired
    SysSalesPermissionMapper sysSalesPermissionMapper;
    @Autowired
    SysNodeConfigMapper sysNodeConfigMapper;
    @Autowired
    SysFlowConfigMapper sysFlowConfigMapper;


    /**
     * 导入审批节点人员
     * @param user
     * @param file
     */
    @Transactional
    public void inputNodePerson(User user, MultipartFile file) {
        ExcelTypeEnum excelType = ExcelTypeEnum.XLSX;
        if (file.getOriginalFilename().endsWith("xls")) {
            excelType = ExcelTypeEnum.XLS;
        }
        List<InputNodePerson> nodePersonList = new ArrayList();
        try {
            ExcelReader reader = new ExcelReader(file.getInputStream(), excelType, null,
                    new AnalysisEventListener<InputNodePerson>() {
                @Override
                public void invoke(InputNodePerson o, AnalysisContext analysisContext) {
                    nodePersonList.add(o);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                }
            });
            reader.read(new com.alibaba.excel.metadata.Sheet(1, 1, InputNodePerson.class));
        } catch (Exception e) {
            throw new BusinessException("解析文件出错");
        }

        log.info("导入数据" + nodePersonList.size() + "条");

        /*开始处理数据*/
        SysFlowConfig sysFlowConfig = sysFlowConfigMapper.selectByPrimaryKey(2);
        List<FlowNodeJSON> flowNodeJSONS = JSON.parseArray(sysFlowConfig.getFlowNode(), FlowNodeJSON.class);
        nodePersonList.forEach(inputNodePerson -> {
            SysNodeConfig startNodeConfig = new SysNodeConfig();
            startNodeConfig.setNodeCode(flowNodeJSONS.get(0).getNode().getCode());
            startNodeConfig.setNodeName(flowNodeJSONS.get(0).getNode().getName());
            startNodeConfig.setProvinceCode(inputNodePerson.getCode());
            NodePerson startNodePerson = new NodePerson();
            List<FlowNodeJSON.Person> startPersonList = new ArrayList<>();
            startNodePerson.setPerson(startPersonList);
            startNodeConfig.setNodePerson(JSON.toJSONString(startNodePerson));
            sysNodeConfigMapper.insertSelective(startNodeConfig);
            if (Objects.nonNull(inputNodePerson.getAreaManager())) {
                SysNodeConfig sysNodeConfig = new SysNodeConfig();
                sysNodeConfig.setNodeCode(flowNodeJSONS.get(1).getNode().getCode());
                sysNodeConfig.setNodeName(flowNodeJSONS.get(1).getNode().getName());
                sysNodeConfig.setProvinceCode(inputNodePerson.getCode());
                NodePerson nodePerson = new NodePerson();
                List<FlowNodeJSON.Person> personList = new ArrayList<>();
                nodePerson.setPerson(personList);
                String[] userIds = inputNodePerson.getAreaManager().split(",");
                for (String userId: userIds) {
                    SysSalesPermission sysSalesPermission = sysSalesPermissionMapper.findByUserId(Long.parseLong(userId));
                    if (Objects.isNull(sysSalesPermission)) {
                        throw new BusinessException("用户不存在：" + userId);
                    }
                    FlowNodeJSON.Person person = new FlowNodeJSON.Person();
                    person.setCode(userId);
                    person.setName(sysSalesPermission.getUserName());
                    personList.add(person);
                }
                sysNodeConfig.setNodePerson(JSON.toJSONString(nodePerson));
                sysNodeConfigMapper.insertSelective(sysNodeConfig);
            }
            if (Objects.nonNull(inputNodePerson.getPlatform())) {
                SysNodeConfig sysNodeConfig = new SysNodeConfig();
                sysNodeConfig.setNodeCode(flowNodeJSONS.get(2).getNode().getCode());
                sysNodeConfig.setNodeName(flowNodeJSONS.get(2).getNode().getName());
                sysNodeConfig.setProvinceCode(inputNodePerson.getCode());
                NodePerson nodePerson = new NodePerson();
                List<FlowNodeJSON.Person> personList = new ArrayList<>();
                nodePerson.setPerson(personList);
                String[] userIds = inputNodePerson.getPlatform().split(",");
                for (String userId: userIds) {
                    SysSalesPermission sysSalesPermission = sysSalesPermissionMapper.findByUserId(Long.parseLong(userId));
                    if (Objects.isNull(sysSalesPermission)) {
                        throw new BusinessException("用户不存在：" + userId);
                    }
                    FlowNodeJSON.Person person = new FlowNodeJSON.Person();
                    person.setCode(userId);
                    person.setName(sysSalesPermission.getUserName());
                    personList.add(person);
                }
                sysNodeConfig.setNodePerson(JSON.toJSONString(nodePerson));
                sysNodeConfigMapper.insertSelective(sysNodeConfig);
            }
            if (Objects.nonNull(inputNodePerson.getFinanceStaff())) {
                SysNodeConfig sysNodeConfig = new SysNodeConfig();
                sysNodeConfig.setNodeCode(flowNodeJSONS.get(3).getNode().getCode());
                sysNodeConfig.setNodeName(flowNodeJSONS.get(3).getNode().getName());
                sysNodeConfig.setProvinceCode(inputNodePerson.getCode());
                NodePerson nodePerson = new NodePerson();
                List<FlowNodeJSON.Person> personList = new ArrayList<>();
                nodePerson.setPerson(personList);
                String[] userIds = inputNodePerson.getFinanceStaff().split(",");
                for (String userId: userIds) {
                    SysSalesPermission sysSalesPermission = sysSalesPermissionMapper.findByUserId(Long.parseLong(userId));
                    if (Objects.isNull(sysSalesPermission)) {
                        throw new BusinessException("用户不存在：" + userId);
                    }
                    FlowNodeJSON.Person person = new FlowNodeJSON.Person();
                    person.setCode(userId);
                    person.setName(sysSalesPermission.getUserName());
                    personList.add(person);
                }
                sysNodeConfig.setNodePerson(JSON.toJSONString(nodePerson));
                sysNodeConfigMapper.insertSelective(sysNodeConfig);
            }
            if (Objects.nonNull(inputNodePerson.getFinanceManager())) {
                SysNodeConfig sysNodeConfig = new SysNodeConfig();
                sysNodeConfig.setNodeCode(flowNodeJSONS.get(4).getNode().getCode());
                sysNodeConfig.setNodeName(flowNodeJSONS.get(4).getNode().getName());
                sysNodeConfig.setProvinceCode(inputNodePerson.getCode());
                NodePerson nodePerson = new NodePerson();
                List<FlowNodeJSON.Person> personList = new ArrayList<>();
                nodePerson.setPerson(personList);
                String[] userIds = inputNodePerson.getFinanceManager().split(",");
                for (String userId: userIds) {
                    SysSalesPermission sysSalesPermission = sysSalesPermissionMapper.findByUserId(Long.parseLong(userId));
                    if (Objects.isNull(sysSalesPermission)) {
                        throw new BusinessException("用户不存在：" + userId);
                    }
                    FlowNodeJSON.Person person = new FlowNodeJSON.Person();
                    person.setCode(userId);
                    person.setName(sysSalesPermission.getUserName());
                    personList.add(person);
                }
                sysNodeConfig.setNodePerson(JSON.toJSONString(nodePerson));
                sysNodeConfigMapper.insertSelective(sysNodeConfig);
            }
            if (Objects.nonNull(inputNodePerson.getCEO())) {
                SysNodeConfig sysNodeConfig = new SysNodeConfig();
                sysNodeConfig.setNodeCode(flowNodeJSONS.get(5).getNode().getCode());
                sysNodeConfig.setNodeName(flowNodeJSONS.get(5).getNode().getName());
                sysNodeConfig.setProvinceCode(inputNodePerson.getCode());
                NodePerson nodePerson = new NodePerson();
                List<FlowNodeJSON.Person> personList = new ArrayList<>();
                nodePerson.setPerson(personList);
                String[] userIds = inputNodePerson.getCEO().split(",");
                for (String userId: userIds) {
                    SysSalesPermission sysSalesPermission = sysSalesPermissionMapper.findByUserId(Long.parseLong(userId));
                    if (Objects.isNull(sysSalesPermission)) {
                        throw new BusinessException("用户不存在：" + userId);
                    }
                    FlowNodeJSON.Person person = new FlowNodeJSON.Person();
                    person.setCode(userId);
                    person.setName(sysSalesPermission.getUserName());
                    personList.add(person);
                }
                sysNodeConfig.setNodePerson(JSON.toJSONString(nodePerson));
                sysNodeConfigMapper.insertSelective(sysNodeConfig);
            }
            SysNodeConfig endNodeConfig = new SysNodeConfig();
            endNodeConfig.setNodeCode(flowNodeJSONS.get(6).getNode().getCode());
            endNodeConfig.setNodeName(flowNodeJSONS.get(6).getNode().getName());
            endNodeConfig.setProvinceCode(inputNodePerson.getCode());
            NodePerson endNodePerson = new NodePerson();
            List<FlowNodeJSON.Person> endPersonList = new ArrayList<>();
            endNodePerson.setPerson(endPersonList);
            endNodeConfig.setNodePerson(JSON.toJSONString(endNodePerson));
            sysNodeConfigMapper.insertSelective(endNodeConfig);
        });
    }
}
